import 'dart:ffi';

import 'storage.dart';
import '../models/pcontent_model.dart';
import 'httpsClient.dart';

class CartServices {
  // 增加购物车
  static addCart(
      PcontentItemtModel pcontent, String selectedAttr, int count) async {
    // 获取本地数据，看是否有没有数据
    List? cartListData = await Storage.getData('cartList');
    if (cartListData != null) {
      // 有数据判断购物车中有没有当前产品
      var hasData = cartListData.any((v) {
        return v["_id"] == pcontent.id && v["selectedAttr"] == selectedAttr;
      });

      if (hasData) {
        // 有产品，让产品数量等于以前的加上现在的
        for (var i = 0; i < cartListData.length; i++) {
          if (cartListData[i]["_id"] == pcontent.id &&
              cartListData[i]["selectedAttr"] == selectedAttr) {
            cartListData[i]["count"] += count;
          }
        }
        // 重新写入
        await Storage.setData('cartList', cartListData);
      } else {
        // 没有产品，把购物车中的数据与当前的数据拼接，拼接后重新写入本都
        cartListData.add({
          "_id": pcontent.id,
          "title": pcontent.title,
          "price": pcontent.price,
          "selectedAttr": selectedAttr,
          "count": count,
          "pic": HttpsClient.replaeUrl(pcontent.pic),
          "checked": true
        });

        await Storage.setData('cartList', cartListData);
      }
    } else {
      // 没有数据，把当前商品数量机属性放在数据中心后，写入本地
      List tempList = [];
      tempList.add({
        "_id": pcontent.id,
        "title": pcontent.title,
        "price": pcontent.price,
        "selectedAttr": selectedAttr,
        "count": count,
        "pic": HttpsClient.replaeUrl(pcontent.pic),
        "checked": true
      });

      await Storage.setData('cartList', tempList);
    }
  }

  // 获取购物车
  static Future<List> getCartData() async {
    List? cartListData = await Storage.getData('cartList');
    if (cartListData != null) {
      return cartListData;
    } else {
      return [];
    }
  }

  // 清空搜索记录
  static clearHistoryData() async {
    await Storage.clear('searchList');
  }

  // 获取选中的cartList数据
  static getCheckedCartData() async {
    List tempList = [];
    List? cartListData = await Storage.getData('cartList');
    if (cartListData != null) {
      for (var i = 0; i < cartListData.length; i++) {
        if (cartListData[i]["checked"] == true) {
          tempList.add(cartListData[i]);
        }
      }
      return tempList;
    } else {
      return [];
    }
  }

  // 保存购物车数据到本地
  static void setCartList(cartListData) async {
    await Storage.setData('cartList', cartListData);
  }
}
